package com.light.model;

import com.light.constant.Constant;
import com.light.util.RandomUtil;
import com.light.util.SwingUtil;
import java.awt.*;
import java.time.LocalDateTime;

/**
 * @Author MoonlightL
 * @ClassName: Pipe
 * @ProjectName flappy_bird
 * @Description: 管道
 * @DateTime 2023/3/13, 0013 17:00
 */
public class Pipe extends GameElement {

    // 上管道图片
    private Image imageDown;

    // 下管道图片
    private Image imageUp;

    private int originX;

    // 上管道 y 坐标
    private int downY;

    // 下管道 y 坐标
    private int upY;

    private int min = -200;

    private int max = 200;

    private volatile boolean flag;

    public Pipe(int x, int y) {
        super(x, y, SwingUtil.getImageIcon("img/pipe_down.png").getImage());
        this.originX = x;
        this.imageDown = SwingUtil.getImageIcon("img/pipe_down.png").getImage();
        this.imageUp = SwingUtil.getImageIcon("img/pipe_up.png").getImage();
        this.downY = RandomUtil.getRandom(this.min, this.max);
        this.upY = this.downY + Constant.PIPE_MARGIN + 340;
    }

    @Override
    public void draw(Graphics2D g) {
        g.drawImage(this.imageDown, this.getX(), this.downY, null);
        g.drawImage(this.imageUp, this.getX(), this.upY, this.getX() + getWidth(), Constant.LAND_Y, 0, 0, getWidth(), Constant.LAND_Y - this.upY, null);
    }

    @Override
    public void reset() {
        this.setX(originX);
        this.flag = false;
    }

    public void keepMove(int x, int y) {
        if (x <= - getWidth()) {
            this.setX(Constant.WIN_WIDTH);
            this.downY = RandomUtil.getRandom(this.min, this.max);
            this.upY = this.downY + Constant.PIPE_MARGIN + 340;
            this.flag = false;
            return;
        }
        this.setX(x);
        this.setY(y);
    }

    public boolean checkHit(Bird bird) {
        int birdX = bird.getX();
        int birdY = bird.getY();
        int birdW = bird.getWidth();
        int birdH = bird.getHeight();

        if (birdX + birdW >= getX() + 6 && birdX + birdW < getX() + getWidth()) {
            if (birdY <= downY + getHeight() - 14) {
                System.out.println("碰到上管道，游戏结束");
                return true;
            }

            if (birdY + birdH >= upY + 12) {
                System.out.println("碰到下管道，游戏结束");
                return true;
            }
        }

        return false;
    }

    public boolean cross(Bird bird) {
        int birdX = bird.getX();

        if (getX() + getWidth() - 12 < birdX && !flag) {
            this.flag = true;
            return true;
        }

        return false;
    }
}
